﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Data;
using System.Reflection;
using System.Text;
using System.IO;
using FreeSql;
using MongoDB.Driver.Core.Configuration;

namespace OkTool.Db
{
    public class SqliteUtil
    {
        /// <summary>
        /// 文件路径
        /// </summary>
        public static string DbPath = AppDomain.CurrentDomain.BaseDirectory + "Data\\data.db";

        /// <summary>
        /// 数据库密码
        /// </summary>
        public static string DbPassWord;

        private static IFreeSql _instance { get; set; }

        private static readonly object _locker = new object();

        /// <summary>
        /// Sqlite实例
        /// </summary>
        /// <returns></returns>
        public static IFreeSql GetInstance()
        {

            if (_instance == null)
            {
                lock (_locker)
                {
                    if (_instance == null)
                    {
                        _instance = new FreeSqlBuilder().UseConnectionString(DataType.Sqlite, $"Data Source={DbPath};Version=3;Password={DbPassWord};").Build();
                    }
                }
            }
            return _instance;

        }

        /// <summary>
        /// 重新实例化IFreeSql
        /// </summary>
        /// <returns></returns>
        public static IFreeSql Reset()
        {
            _instance = new FreeSqlBuilder().UseConnectionString(DataType.Sqlite, $"Data Source={DbPath};Version=3;Password={DbPassWord};").Build();
            return _instance;
        }
        private static bool Open()
        {
            try
            {
                GetInstance().Ado.ExecuteNonQuery("select count(*) from sqlite_master where type='table'");
                return true;

            }
            catch (Exception e)
            {
                return false;
            }
        }
#if NET451 || NET452 || NET46 || NET461
        /// <summary>
        /// 修改数据库密码,需要安装指定版本
        /// NuGet\Install-Package System.Data.SQLite.Core -Version 1.0.112
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static bool ChangePass(string pwd)
        {

            try
            {
                SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder();
                sb.DataSource = DbPath;
                sb.Version = 3;
                sb.Password = DbPassWord;
                using (var con = new SQLiteConnection(sb.ToString()))
                {
                    con.Open();
                    con.ChangePassword(pwd);
                    DbPassWord = pwd;
                    return true;
                }


            }
            catch (Exception e)
            {
                return false;
            }
        }
#endif
        /// <summary>
        /// 初始化数据库
        /// <para>默认路径当前程序文件夹下Data\\data.db</para>
        /// <para>可以设置密码,配置DbPassWord即可</para>
        /// </summary>
        /// <param name="entities">实体类,文件不存在时需要传入,已存在可以不传</param>
        /// <returns>1成功,0失败</returns>
        public static int InitSqlite(params Type[] entities)
        {
            //数据库判断
            if (!File.Exists(DbPath))
            {
                //数据库文件不存在

                if (entities == null)
                {
                    return 0;
                }

                GetInstance().CodeFirst.SyncStructure(entities);
                //GetInstance().DbMaintenance.CreateIndex("NumberInfo", new string[] { "QQ" }, true);
                return 1;
            }
            else
            {
                return Open() == true ? 1 : 0;
            }

        }
    }
}
